<template>
  <div>
    <div class="btns-wrap">
      <Button
        v-if="showBtn('设置')"
        type="primary"
        @click="addMarketAttrFun"
        >设置</Button
      >
      <Button
        v-if="showBtn('批量更新主推')"
        type="primary"
        @click="handleBatchUpdate('push')"
        >批量更新主推</Button
      >
      <Button
        v-if="showBtn('批量更新新上')"
        type="primary"
        @click="handleBatchUpdate('new')"
        >批量更新新上</Button
      >
      <Button
        type="primary"
        :loading="exportLoading"
        @click="handleExport"
        >导出</Button
      >
    </div>
    <!-- 表格内容 start  -->
    <Table
      ref="table"
      :columns="columns"
      :data="tableDataList"
      :loading="loading"
      height='500'
      class="ivu-mt"
      stripe
      border
      @on-filter-change="handleFilterChange"
      @on-select="handleSelect"
      @on-select-cancel="handleSelectCancel"
      @on-select-all="handleSelectAll"
      @on-select-all-cancel="handleSelectAllCancel"
    >
      <template slot-scope="{ row }" slot="mainPlatform">
        <span v-if="row.mainPlatform === '1'">全部</span>
        <span v-if="row.mainPlatform === '2'">云彩</span>
        <span v-if="row.mainPlatform === '3'">线上</span>
      </template>
      <template slot-scope="{ row }" slot="state">
        <span v-if="row.state === '1'">启用</span>
        <span v-if="row.state === '2'">禁用</span>
      </template>
      <template slot-scope="{ row }" slot="promotionAttr">
        <span v-if="row.promotionAttr === '1'">主推</span>
        <span v-if="row.promotionAttr === '2'">新上</span>
        <span v-if="row.promotionAttr === '3'">积压促销</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <table-actions
          :requestApi="listData.requestApi"
          :basePath="basePath"
          :rowData="row"
          :indexData="index"
          @actionsChange="getData"
        ></table-actions>
      </template>
    </Table>
    <!-- 表格内容 end  -->
    <!-- 分页 start  -->
    <div class="ivu-mt ivu-text-center">
      <Page
        :total="totalNum"
        show-total
        show-sizer
        transfer
        :current.sync="nowPage"
        @on-change="getData"
        @on-page-size-change="handleChangePage"
      />
    </div>
    <bacth-update-dialog
      :dialogVisible="dialogVisible"
      :dialogType="dialogType"
      @handleCloseDialog="handleCloseDialog"
    />
    <!-- 分页 end  -->
  </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex';
import util from '@/libs/util';
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import tables from '@/mixins/dynamictable'; // 混入通用代码
import qwInput from '@/components/common/formItem/qwInput'; // 表单input组件
import qwSelect from '@/components/common/formItem/qwSelect'; // 表单select组件
import qwDatePicker from '@/components/common/formItem/qwDatePicker'; // 表单日期组件
import qwSelectTree from '@/components/common/formItem/qwSelectTree'; // 表单下拉树组件
import tableActions from './tableActions'; // 表格操作项
import tableBtns from './tableBtns'; // 表格内部操作按钮
import BacthUpdateDialog from './bacthUpdateDialog.vue'
import { getBtnsId } from '@/libs/btnsPermission';
export default {
  mixins: [tables],
  props: {
    dynamicData: {
      type: Object
    },
    pagePath: {
      type: String
    },
    orderState: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState('admin/baseList', [
      'listData',
      'searchFormData',
      'searchFormDataQ'
    ]),
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  watch: {
    orderState (n, o) {
      this.getData();
    }
  },
  components: {
    qwInput,
    qwSelect,
    qwDatePicker,
    qwSelectTree,
    tableActions,
    tableBtns,
    BacthUpdateDialog
  },
  data () {
    return {
      exportLoading: false,
      util: util,
      basePath: this.dynamicData.basePath, // 拼接基础路径
      uuids: [],
      version: 0,
      dialogVisible: false,
      dialogType: '',
    };
  },
  created () {},
  methods: {
    ...mapMutations('admin/baseList', ['setTableRowData']),
    // 获取表格的数据
    getData () {
      /* let searchParam = [];
      Object.keys(this.searchFormData).forEach((key) => {
        searchParam.push({ name: key, value: this.searchFormData[key] });
      });
      Object.keys(this.searchFormDataQ).forEach((key) => {
        searchParam.push({ name: key, value: this.searchFormDataQ[key] });
      }); */

      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        ...this.searchFormData
        /* searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: '' */
      };
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.loading = true;
      // 开始请求列表
      ApiRequest(
        this.listData.requestApi.getTableList.url,
        this.listData.requestApi.getTableList.type,
        data
      ).then((res) => {
        let rData = res;
        if (rData.retData !== '') {
          rData.retData = rData.retData;
        }
        let tableDataList = rData.retData.results;
        tableDataList.forEach((item) => {
          let actions = [];
          if (item.state === '1' && this.showBtn('启停')) {
            actions.push({
              name: 'Alert',
              label: '禁用',
              handleType: 'disable'
            });
          } else {
            if (this.showBtn('启停')) {
              actions.push({
                name: 'Alert',
                label: '启用',
                handleType: 'enable'
              });
            }
          }
          item.actions = actions;
        });
        // 增加表格操作项
        this.tableDataList = rData.retData.results;
        this.totalNum = rData.retData.totalNum;
        this.loading = false;
      });
    },
    handleSelect (row) {
      this.uuids = [];
      row.forEach((element) => {
        this.uuids.push(element.uuid);
        this.version = element.version;
      });
    },
    handleSelectAll (row) {
      this.uuids = [];
      row.forEach((element) => {
        this.uuids.push(element.uuid);
        this.version = element.version;
      });
      this.version = row.version;
    },
    handleSelectAllCancel (row) {
      this.uuids = [];
      this.version = 0;
    },
    addMarketAttrFun () {
      if (this.uuids.length == 0) {
        return this.$Message.error('请选择要设置的营销属性!');
      }
      let curBtnId = getBtnsId('设置');
      sessionStorage.setItem('buttonId', curBtnId);
      this.$router.push({
        path: '/commodity/commodityManage/marketingAttrManage/marketingAttrManageAdd',
        query: { uuids: this.uuids.join(','), version: this.version }
      });
    },
    // 批量更新主推新上
    handleBatchUpdate (type) {
      this.dialogVisible = true;
      this.dialogType = type;
    },
    handleCloseDialog () {
      this.dialogVisible = false;
    },
    // 导出
    handleExport () {
      this.exportLoading = true;
      ApiRequestExportTable(
        '/sysback/manage/productmanagerattrskurel/exportExcel',
        'post',
        this.searchFormData
      )
        .then((res) => {
          this.exportLoading = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = `商品营销属性管理.xlsx`;
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.exportLoading = false;
          this.$message.error('导出失败');
        });
    }
  }
};
</script>
<style lang="less" scoped>
.i-table-no-border .ivu-table-header th {
  background: #f8f8f8;
}
.btns-wrap {
  button {
    margin-right: 5px;
  }
}
</style>
